<template>
    <div class="User-Set-main">
        <van-nav-bar left-arrow @click-left="onClickLeft">
            <template #left>
                <van-icon :name="backicon" size="20"/>
            </template>
            <template #title>
                <span class="hometitle">设置</span>
            </template>
        </van-nav-bar>

        <div class="user-main">
            <div class="header">
                <div class="bg-top" align="center">
                    <div class="header-ava">
                        <img class="avatar" :src="UserInfo.head_pic.indexOf('http:')>-1?`${UserInfo.head_pic}`:`http://www.starrymedia.vip${UserInfo.head_pic}`" alt="">
                    </div>
                    <img class="avataricon" src="../../assets/img/camera.png" @click="uploadavater" alt="">
                </div>
                <div class="user-nickname">
                    <span class="nickname" v-if="!editnicks" @click="editnick">{{MyNickName}}</span>
                    <span class="nickname" v-if="editnicks">
                        <input type="text" ref="usernickname" @blur="editnick" style="color:#999;" v-model="MyNickName">
                    </span>
                    <!-- <img class="nickedit" :src="!editnicks?editicon:editiconact" @click="editnick" alt=""> -->
                </div>
            </div>

            <div class="info-li">
                用户名
                <span>{{UserInfo.nickname}}</span>
            </div>
            <div class="info-li">
                ID
                <span>{{UserInfo.user_code}}</span>
            </div>
            <div class="info-li">
                手机号
                <span>{{UserInfo.mobile | outphone}}</span>
            </div>
            <div class="info-li" @click="showsex=true">
                性别
                <span v-if="UserInfo.sex==0">保密</span>
                <span v-if="UserInfo.sex>0"><img class="user-sex" :src="UserInfo.sex==1?man:woman" alt=""></span>
            </div>
            <div class="info-li" @click="showbirth=true">
                生日
                <span>{{UserInfo.birthday?UserInfo.birthday:"点击选择"}}</span>
            </div>
            <div class="info-li" @click="JUMPtoupdate">
                密码管理
                <span><img class="pwdmore" :src="pwdmore" alt=""></span>
            </div>
            <div class="info-li" @click="jumptoaddress">
                地址管理
                <span><img class="pwdmore" :src="pwdmore" alt=""></span>
            </div>
        </div>

        <img class="outLogin" @click="logout" :src="outLogin" alt="">


        <van-popup v-model="showbirth" position="bottom" :style="{ height: '30%' }" >
            <van-datetime-picker
                type="date"
                :min-date="minDate"
                :max-date="maxDate"
                @confirm="dateconfirm"
                title="选择年月日"/>
        </van-popup>

        <van-popup v-model="showsex" position="bottom" :style="{ height: '30%' }" >
            <!-- <van-cell-group>
                <van-cell title="男" @click="changeSex(1)">
                    <template #right-icon>
                        <van-icon :name="man" style="line-height: inherit;" />
                    </template>
                </van-cell>
                <van-cell title="女" @click="changeSex(2)">
                    <template #right-icon>
                        <van-icon :name="woman" style="line-height: inherit;" />
                    </template>
                </van-cell>
            </van-cell-group> -->
            <!-- <span class="top-size-title-1">性 <span class="letter-spacing"></span> 别</span> -->
            <van-picker
                show-toolbar
                title="性别"
                @confirm="onsexConfirm"
                @cancel="showsex=false"
                :columns="listData" :visible-item-count="3" item-height="40" :default-index="0"/>
        </van-popup>
    </div>
</template>
<script>
import {_ajaxindex,_changeUserInfo} from '../../service/user'
import {_getmedia,_getjsapiticket} from '../../service/wxService.js'
export default {
    data(){
        return{
            backicon:require('../../assets/img/backicon.png'),
            editicon:require('../../assets/img/nickicon.png'),
            editiconact:require('../../assets/img/editicon.png'),
            man:require('../../assets/img/man.png'),
            woman:require('../../assets/img/woman.png'),
            pwdmore:require('../../assets/img/usersetmorepwd.png'),
            outLogin:require('../../assets/img/outLogin.png'),

            minDate: new Date(1960, 0, 1),
            maxDate: new Date(2025, 10, 1),
            UserInfo:{},
            showbirth:false,
            showsex:false,
            editnicks:false,
            listData: ["保密","男","女"],
            MyNickName:"",
        }
    },
    mounted(){
        this.getUserData()
    },
    filters:{
        outphone(val){
            try{
                return val.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
            }catch(e){

            }
        }
    },
    methods:{
        onsexConfirm(value, index){
            console.log(value,index)
            this.UserInfo.sex=index
            this.showsex=false
            this.EditUser()
        },
        jumptoaddress(){
            this.$router.push("/manageaddress")
        },
        JUMPtoupdate(){
            this.$router.push("/password/update")
        },
        onClickLeft(){
            this.$router.push("/own")
        },
        logout(){
            localStorage.removeItem("WxUserInfo")
            localStorage.removeItem("user")
            localStorage.removeItem("WxCode")
            // localStorage.removeItem("showAD")
            this.$router.push("/login")
        },
        getUserData(){
            let _this=this
            if(localStorage.getItem("user")==null||localStorage.getItem("user")==undefined){
                this.$router.push("/login")
            }
            let uid=JSON.parse(localStorage.getItem("user")).user_id
            _ajaxindex({user_id:uid}).then(res=>{
                console.log(res)
                if(res.errcode==1){
                    this.UserInfo=res.data
                    this.MyNickName=res.data.nickname
                }
            })
        },
        dateconfirm(date){
            console.log(date)
            let datestr=moment(date).format('YYYY-MM-DD')
            this.UserInfo.birthday=datestr
            this.showbirth=false
            this.EditUser()
        },
        changeSex(val,index){
            // console.log(val)
            // console.log(index)
            // this.UserInfo.sex=i
            // this.showsex=false
            // this.EditUser()
        },
        editnick(){
            if(!this.editnicks){
                this.editnicks=true
                this.$nextTick((x)=>{   //正确写法
                    this.$refs.usernickname.focus();
                })
            }else{
                this.editnicks=false
                this.EditUser()
            }
        },
        async uploadavater(){
            var _this = this,imageLength=9;
            var image={localIds:[],serverId:[]};　　//接收微信接口返回的参数
            var imageUrlList=[]　　//用户绑定页面上显示图片的变量
            var mediaIds=[] //接收上传图片返回的serverId（该字段就是调用获取临时素材接口的媒体ID）


            _this.$toast.loading({
                duration: 0, // 持续展示 toast
                forbidClick: true,
            })
            let localhref=window.location.href
            // let localhref="http://market.starrymedia.vip"
            let uid= JSON.parse(localStorage.getItem("user")).user_id
            let access_token=JSON.parse(localStorage.getItem("WXjsapi_ticket")).access_token
            // alert("开始更换")
            await _getjsapiticket(localhref).then(res=>{
                console.log("_getjsapiticket",res)
                if(res.errcode==1){
                    localStorage.setItem("WXjsapi_ticket",JSON.stringify(res.data))
                    wx.config({
                        debug: false, 
                        appId: res.data.appid, // 必填，公众号的唯一标识
                        timestamp: res.data.timestamp, // 必填，生成签名的时间戳
                        nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
                        signature: res.data.signature,// 必填，签名，见附录1
                        jsApiList: [
                            "uploadImage","chooseImage","downloadImage"
                        ]
                    });
                    
                    setTimeout(()=>{
                        wx.ready(()=>{
                            wx.chooseImage({
                                count: 1, //上传图片的张数，最多上传9张
                                sizeType: ['original', 'compressed'],　　// 可以指定是原图还是压缩图，默认二者都有
                                sourceType: ['album', 'camera'],　　// 可以指定来源是相册还是相机，默认二者都有
                                success: function(res1) {
                                    console.log("uploadavater",res1)
                                    // alert("fff")
                                    wx.uploadImage({
                                        localId:res1.localIds[0],
                                        success: function(res2) {
                                            console.log("uploadImageSuccess",JSON.stringify(res2))
                                            try{
                                                _getmedia({
                                                    access_token:access_token,
                                                    media_id:res2.serverId,
                                                    user_id:uid
                                                }).then(res=>{
                                                    // _this.header=res.data
                                                    _this.getUserData()
                                                    _this.$toast.clear()
                                                })
                                            }catch(e){
                                                _this.$toast("catch",JSON.stringify(e))
                                            }
                                        },
                                        fail: function(e2) {
                                            console.log("uploadImageError",JSON.stringify(e2));
                                        }
                                    });
                                },
                                fail: function(e1) {
                                    console.log("uploadavater error",e1)
                                }
                            });
                        })
                        wx.error(function(res){
                            // window.location.href=window.location.href
                            // alert(JSON.stringify(res))
                            _this.$toast.clear()
                        });
                    },400)
                }
            })
            _this.$toast.clear()
            
        },
        EditUser(){
            let _this=this
            _this.$toast.loading({
                duration: 0, // 持续展示 toast
                forbidClick: true,
            })
            _changeUserInfo({
                user_id:this.UserInfo.user_id,
                nickname:this.MyNickName,
                sex:this.UserInfo.sex,
                birthday:this.UserInfo.birthday
            }).then(res=>{
                setTimeout(()=>{
                    _this.$toast.clear()
                    if(res.errcode==1){
                        _this.getUserData()
                    }else{
                        _this.$toast("编辑失败")
                    }
                },1000)
            })
        }
    }
}
</script>
<style lang="less" scoped>
.font-SC(){
    font-family: "PingFang SC","Microsoft YaHei";
}
.User-Set-main{
    width: 100%;
    height: 100vh;
    overflow-y: auto;
    background-color: #fff;
    .hometitle{
        font-size: 18px;
        .font-SC();
        font-weight: bold;
        color: #000;
        line-height: 46px;
    }
    .user-main{
        width: 100%;
        height: auto;
        padding: 15px;

        .header{
            width: 100%;
            height: 203px;
            border-bottom: 1px solid #e6e6e6;
            .bg-top{
                width: 100%;
                height: 130px;
                border-radius:10px 10px 0 0;
                // background-color: #ccc;
                background-image: url('../../assets/img/useSetting-bg.jpg');
                background-position: center;
                background-repeat: no-repeat;
                background-size: contain;
                padding-top: 60px;
                .header-ava{
                    width: 93px;
                    height: 93px;
                    border:7px solid #fff;
                    border-radius: 47px;
                    overflow: hidden;
                    // background-color: #0170c1;
                    .avatar{
                        display: block;
                        width: 79px;
                        height: 79px;
                        overflow: hidden;
                        // border-radius: 47px;
                    }
                }
                .avataricon{
                    width: 23px;
                    height: 23px;
                    margin: -52px 0 0 63px;
                }
            }
            .user-nickname{
                width: 100%;
                height: 44px;
                margin-top: 28px;
                line-height: 44px;
                .nickname{
                    .font-SC();
                    font-weight: bolder;
                    font-size: 15px;
                    color: #000;
                    display: block;
                    text-align: center;
                    input{
                        background:none;  
                        outline:none;  
                        border:none;
                        height: 30px;
                        width: 50%;
                        line-height: 30px;
                        .font-SC();
                        font-size: 15px;
                        color: #000;
                        caret-color:#000;
                        // padding-left: 12px;
                        caret-color:#000 !important;
                        text-align: center;
                    }
                }
                .nickedit{
                    width: 16px;
                    float: right;
                    margin-right: 25px;
                    margin-top: -30px;
                }
            }
        }
        .info-li{
            width: 100%;
            height: 52px;
            line-height: 50px;
            text-align: left;
            .font-SC();
            font-size: 12px;
            color: #333;
            font-weight: bold;
            span{
                float: right;
                color: #999;
                .user-sex{
                    width: 13px;

                }
                .pwdmore{
                    width: 10px;
                }
            }
        }
    }
    .outLogin{
        width: 345px;
        margin: 19px auto 40px auto;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    /deep/.van-picker-column__item{
        .font-SC();
        color: #cdcdcd;
        font-size: 13px;
    }
    /deep/.van-picker-column__item--selected{
        .font-SC();
        color: #333;
        font-size: 16px;
    }
    /deep/.van-popup{
        box-shadow: 0 0 20px rgba(51, 51, 51, .1);
    }
    .top-size-title-1{
        display: block;
        width: 100%;
        text-align: center;
        font-family: "PingFang SC","Microsoft YaHei";
        color: #474646;
        font-size: 13px;
        background-color: #fff;
        margin-top: 10px;
        margin-bottom: 10px;
        // background-color: #f2f2f2;
    }
}
</style> 